package com.web.kdl.config;

import com.web.kdl.common.result.CommonResult;
import org.apache.commons.lang3.StringUtils;
import org.simpleframework.xml.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
public class GlobalExceptionHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public CommonResult BindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<String> msgList = new ArrayList<>();
        //将错误信息放在msgList
        bindingResult.getFieldErrors().stream().forEach(item->msgList.add(item.getDefaultMessage()));
        //拼接错误信息
//        String msg = StringUtils.join(msgList, ",");
        String msg = msgList.get(0);
        logger.error("【Vaild异常】{}",msg);
        return CommonResult.error(msg);
    }


    
    /**
     * 處理STOMP消息異常
     */
    @MessageExceptionHandler
    @SendToUser("/queue/errors")
    public CommonResult handleStompException(Exception ex) {
        logger.error("STOMP消息處理異常: {}", ex.getMessage(), ex);
        return CommonResult.error("STOMP處理失敗: " + ex.getMessage());
    }
    
    /**
     * 處理一般WebSocket異常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResult handleException(Exception ex) {
        logger.error("系統異常: {}", ex.getMessage(), ex);
        return CommonResult.error("系統錯誤: " + ex.getMessage());
    }
} 